<?php
/**********************************************************************************
 
 	Displays scan data from Auctioneer for an item.
	
	Copyright (C) 2010 Benjamin Thomas
 
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 	Author: Benjamin Thomas
	Email: thomas.ben@gmail.com
 	Created: 06.22.10
 	Revised: 
 
	Inputs: graph_limit - Number of days to display on graph (default is 7)
			table_limit - Number of days to display in table (default is 30)
			item - Item to search for
 	Calls: 
 
 ***********************************************************************************
 */

require_once(dirname(__FILE__) . '/../../lib/PageLayout.php');
require_once(dirname(__FILE__) . '/../../lib/dateFunctions.php');
require_once(dirname(__FILE__) . '/../../lib/MarketDB.php');

$graph_limit = 7;
$graph_limit_max = 30;
$graph_limit_accept = array(7, 14, 30);
$oneDay = 60*60*24;
if (array_key_exists('limit', $_GET)) {
	$graph_limit = intval($_GET['limit']);
	if ( in_array($graph_limit,$graph_limit_accept) == false ) {
		$graph_limit = 14;
	} elseif ($_GET['limit'] > $graph_limit_max) {
		$graph_limit = $graph_limit_max;
	} 
}
if (array_key_exists('id', $_GET)) {
	$id = intval($_GET['id']);
} else {
	include("index.php");
	//echo "No itemId supplied. Exiting.";
	exit();
}


// Instance a new Database
$marketDB = new MarketDB();
$item = $marketDB->getItem($id);

$minData = createTimestampArray($graph_limit);
$maxData = createTimestampArray($graph_limit);
$countData = createTimestampArray($graph_limit);
$average = createTimestampArray($graph_limit);
$stdMax = createTimestampArray($graph_limit);
$stdMin = createTimestampArray($graph_limit);
$null = createTimestampArray($graph_limit);
$data = $marketDB->getScanSummary($id, $graph_limit);

foreach ($data as &$row) {
	$i = array_search(array(strtotime($row['date']) * 1000,0), $countData);
	$minData[$i][1] = $row['min'] / 10000;
	$maxData[$i][1] = $row['max'] / 10000;
	$countData[$i][1] = $row['total'];
	$average[$i][1] = $row['avg'] / 10000;
	$stdMax[$i][1] = $average[$i][1] + ($row['stddev'] / 10000);
	$stdMin[$i][1] = $average[$i][1] - ($row['stddev'] / 10000);
}

if (!$icon = $item['icon']) {
	$icon = "404.png";
}
$icon = '<img src="images/icons/'. $icon . '" style="height:20px; width: 20px; margin-right: 5px;" />';
echo '<div style="margin-top: 20px;">' . $icon . ' ' . $item['name'] . '<br /></div>';
$top = array();
$top[] = "<a href='#' onClick='showSales($graph_limit, $id)' class='small'>Sales</a>";
if ($graph_limit != 7) { $top[] = "<a href='#limit=7&id=$id' onClick='showScans(7, $id)' class='small'>Last 7 Days</a>"; }
if ($graph_limit != 14) { $top[] = "<a href='#limit=14&id=$id' onClick='showScans(14, $id)' class='small'>Last 14 Days</a>"; }
if ($graph_limit != 30) { $top[] = "<a href='#limit=30&id=$id' onClick='showScans(30, $id)' class='small'>Last 30 Days</a>"; }
echo  implode(" | ", $top);
unset($top);
print "<hr />";

print "<div style='width: 900px; text-align: center;'></div>";
print '<div id="placeholder" class="graph" style="width:900px;height:300px; text-align:center">';
print "<img src='images/indicator.gif' style='margin-left: auto; margin-right: auto' alt='loading...' />";
print '<br />Your graph is loading.</div>' . "\n\n";
echo '<div>';
?>
<script id="source" language="javascript" type="text/javascript">
$(function () {
	$('#placeholder').bind('click', function() { $(".legend").toggle(); });
	var rd = [];
	rd[0] = <?php echo json_encode($countData); ?>;
	rd[1] = <?php echo json_encode($average); ?>;
	rd[2] = <?php echo json_encode($minData); ?>;
	rd[3] = <?php echo json_encode($maxData); ?>;
	rd[4] = <?php echo json_encode($stdMin); ?>;
	rd[5] = <?php echo json_encode($stdMax); ?>;

	for (var j = 0; j < rd.length; ++j)
		for (var i = 0; i < rd[j].length; ++i)
			rd[j][i][0] +=  <?php echo getOffset(); ?> * 1000;
 
    var options = {
        xaxis: { mode: "time", timeformat: "%m/%d" },
		yaxes: [
			{ position: 'left' },
			{ position: 'left' },
			{ position: 'right' },
		],
		yaxis: { min: 0 },
		legend: { position: 'nw' },
		grid: { hoverable: true }
    };
	
	var d = [
		{ data: rd[0], type: 'int', label: "Total Seen", color: "rgb(175,216,248)", yaxis: 3, lines: { show: false }, bars: { show: true, align: 'center', barWidth: 60*60*24*1000 } },
		{ data: rd[1], type: 'gold', label: 'Average', color: "rgb(203,75,7)", lines: { show: true } },
		{ data: rd[2], type: 'gold', tooltip: 'Min Price Seen', label: 'Prices Seen', id: 'seen', color: "rgb(73,106,204)", lines: { show: false } },
		{ data: rd[3], type: 'gold', tooltip: 'Max Price Seen', lines: { show: false, fill: 0.25 }, color: "rgb(73,106,204)", fillBetween: 'seen' },
		{ data: rd[4], type: 'gold', tooltip: 'Stddev Min', label: 'Standard Deviation', id: 'stddev', color: "rgb(77,167,77)", lines: { show: true } },
		{ data: rd[5], type: 'gold', tooltip: 'Stddev Max',lines: { show: true, fill: 0.25 }, color: "rgb(77,167,77)", fillBetween: 'stddev' }
	]
	
	var plot = $.plot($("#placeholder"), d, options);	
 
    var previousPoint = null;
	var monthname=new Array("January","February","March","April","May","June","July","August","September","Octber","November","December");
    $("#placeholder").bind("plothover", function (event, pos, item) {
        $("#x").text(pos.x.toFixed(2));
        $("#y").text(pos.y.toFixed(2));
 
		if (item) {
			if (previousPoint != item.datapoint) {
				previousPoint = item.datapoint;
				
				$("#tooltip").remove();
				var x = new Date(item.datapoint[0]);
				x = monthname[x.getMonth()] + " " + x.getDate();
				var y = item.datapoint[1];
				showToolTip(item, x, y);
			}
		}
		else {
			$("#tooltip").remove();
			previousPoint = null;            
		}
    });
	$('.legendColorBox').live('click', function() {
		var s =  $(this).siblings().text(); 
		if (s == 'Total Seen')
			d[0]['bars']['show'] = !d[0]['bars']['show'];
		if (s == 'Average')
			d[1]['lines']['show'] = !d[1]['lines']['show'];
		if (s == 'Prices Seen') {
			d[2]['lines']['show'] = !d[2]['lines']['show'];
			d[3]['lines']['show'] = !d[3]['lines']['show'];
		}
		if (s == 'Standard Deviation') {
			d[4]['lines']['show'] = !d[4]['lines']['show'];
			d[5]['lines']['show'] = !d[5]['lines']['show'];
		}
		var plot = $.plot($("#placeholder"), d, options);	
	});

});
</script> 

